﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Threading.Thread;
using static System.Console;

namespace TaskUnitProject
{
    /// <summary>
    /// 2.1 Parallel.Invoke StopWatch
    /// </summary>
    public class TaskUnit_2_1
    {
        /// <summary>
        /// 计时器，准确的测量运行时间
        /// </summary>
        public static Stopwatch stopwatch=new Stopwatch();
        public static void Go()
        {
            //ParallelInvokeMethod();
            ParallelForMethod();
        }

        private static void Run1()
        {
            Sleep(1000);
            WriteLine("任务一花费1秒");
        }

        private static void Run2()
        {
            Sleep(2000);
            Console.WriteLine("任务二花费2秒");
        }

        private static void Run3()
        {
            Sleep(3000);
            WriteLine("任务三花费3秒");
        }

        /// <summary>
        /// 使用Parallel.Invoke(Run1, Run2, Run3);尽可能并行执行每个操作
        /// </summary>
        private static void ParallelInvokeMethod()
        {
            stopwatch.Start();//开始计时
            Parallel.Invoke(Run1, Run2, Run3);
            stopwatch.Stop();//停止计时
            WriteLine($"使用Parallel运行花费时间：{stopwatch.ElapsedMilliseconds}");
            stopwatch.Reset();
            stopwatch.Restart();
            Run1();
            Run2();
            Run3();
            WriteLine($"正常运行花费时间：{stopwatch.ElapsedMilliseconds}");
        }
        private long num = 0;
        private static void ParallelForMethod()
        {
            stopwatch.Restart();
            for (int i = 0; i < 10000; i++)
            {
                for (int j = 0; j < 60000; j++)
                {
                    int sum = 0;
                    sum += i;
                }
            }
            stopwatch.Stop();
            WriteLine($"正常运行花费时间：{stopwatch.ElapsedMilliseconds } ms.");
            stopwatch.Restart();
            Parallel.For(0, 10000, item =>
            {
                for (int j = 0; j < 60000; j++)
                {
                    int sum = 0;
                    sum += item;
                }
            });
            Parallel.For(0, 1000, new ParallelOptions() {MaxDegreeOfParallelism = 5}, item => { });
            List<string> strs=new List<string>(new []{"das","dsadas","aaaa","dsadas"});
            //MaxDegreeOfParallelism = 5，设置最大并发数
            Parallel.ForEach(strs, new ParallelOptions(){MaxDegreeOfParallelism = 5},item =>
            {
                WriteLine(item);
            });
            stopwatch.Stop();
            WriteLine($"使用Parallel运行花费时间：{stopwatch.ElapsedMilliseconds } ms.");
        }
    }
}
